package com.gzmu.myprint.wx.media;

import com.gzmu.myprint.wx.util.ParamesAPI;
import com.gzmu.myprint.wx.util.WeixinUtil;
import net.sf.json.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

public class MUDload {
	public static WeixinMedia uploadMedia(String accessToken, String type, String mediaFileUrl) {
		WeixinMedia weixinMedia = null;
		// 鎷艰璇锋眰鍦板潃
		String uploadMediaUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
		uploadMediaUrl = uploadMediaUrl.replace("ACCESS_TOKEN", accessToken).replace("TYPE", type);

		// 瀹氫箟鏁版嵁鍒嗛殧绗�
		String boundary = "------------7da2e536604c8";
		try {
			URL uploadUrl = new URL(uploadMediaUrl);
			HttpURLConnection uploadConn = (HttpURLConnection) uploadUrl.openConnection();
			uploadConn.setDoOutput(true);
			uploadConn.setDoInput(true);
			uploadConn.setRequestMethod("POST");
			// 璁剧疆璇锋眰澶碈ontent-Type
			uploadConn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
			// 鑾峰彇濯掍綋鏂囦欢涓婁紶鐨勮緭鍑烘祦锛堝線寰俊鏈嶅姟鍣ㄥ啓鏁版嵁锛�
			OutputStream outputStream = uploadConn.getOutputStream();

			URL mediaUrl = new URL(mediaFileUrl);
			HttpURLConnection meidaConn = (HttpURLConnection) mediaUrl.openConnection();
			meidaConn.setDoOutput(true);
			meidaConn.setRequestMethod("GET");

			// 浠庤姹傚ご涓幏鍙栧唴瀹圭被鍨�
			String contentType = meidaConn.getHeaderField("Content-Type");
			// 鏍规嵁鍐呭绫诲瀷鍒ゆ柇鏂囦欢鎵╁睍鍚�
			String fileExt = WeixinUtil.getFileEndWitsh(contentType);
			// 璇锋眰浣撳紑濮�
			outputStream.write(("--" + boundary + "\r\n").getBytes());
			outputStream.write(String.format("Content-Disposition: form-data; name=\"media\"; filename=\"file1%s\"\r\n", fileExt).getBytes());
			outputStream.write(String.format("Content-Type: %s\r\n\r\n", contentType).getBytes());

			// 鑾峰彇濯掍綋鏂囦欢鐨勮緭鍏ユ祦锛堣鍙栨枃浠讹級
			BufferedInputStream bis = new BufferedInputStream(meidaConn.getInputStream());
			byte[] buf = new byte[8096];
			int size = 0;
			while ((size = bis.read(buf)) != -1) {
				// 灏嗗獟浣撴枃浠跺啓鍒拌緭鍑烘祦锛堝線寰俊鏈嶅姟鍣ㄥ啓鏁版嵁锛�
				outputStream.write(buf, 0, size);
			}
			// 璇锋眰浣撶粨鏉�
			outputStream.write(("\r\n--" + boundary + "--\r\n").getBytes());
			outputStream.close();
			bis.close();
			meidaConn.disconnect();

			// 鑾峰彇濯掍綋鏂囦欢涓婁紶鐨勮緭鍏ユ祦锛堜粠寰俊鏈嶅姟鍣ㄨ鏁版嵁锛�
			InputStream inputStream = uploadConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			StringBuffer buffer = new StringBuffer();
			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 閲婃斁璧勬簮
			inputStream.close();
			inputStream = null;
			uploadConn.disconnect();

			// 浣跨敤JSON-lib瑙ｆ瀽杩斿洖缁撴灉
			JSONObject jsonObject = JSONObject.fromObject(buffer.toString());
			weixinMedia = new WeixinMedia();
			weixinMedia.setType(jsonObject.getString("type"));
			// type绛変簬 缂╃暐鍥撅紙thumb锛� 鏃剁殑杩斿洖缁撴灉鍜屽叾瀹冪被鍨嬩笉涓�鏍�
			if ("thumb".equals(type))
				weixinMedia.setMediaId(jsonObject.getString("thumb_media_id"));
			else
				weixinMedia.setMediaId(jsonObject.getString("media_id"));
			    weixinMedia.setCreatedAt(jsonObject.getInt("created_at"));
		} catch (Exception e) {
			weixinMedia = null;
			String error = String.format("涓婁紶濯掍綋鏂囦欢澶辫触锛�%s", e);
			System.out.println(error);
		}
		return weixinMedia;
	}
	
	/**
	 * 鑾峰彇濯掍綋鏂囦欢
	 * @param accessToken 鎺ュ彛璁块棶鍑瘉
	 * @param media_id 濯掍綋鏂囦欢id
	 * @param savePath 鏂囦欢鍦ㄦ湇鍔″櫒涓婄殑瀛樺偍璺緞
	 * */
	public static String downloadMedia(String accessToken, String mediaId, String savePath) {
		String filePath = null;
		// 鎷兼帴璇锋眰鍦板潃
		String requestUrl = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
		requestUrl = requestUrl.replace("ACCESS_TOKEN", accessToken).replace("MEDIA_ID", mediaId);
		System.out.println(requestUrl);
		try {
			URL url = new URL(requestUrl);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setDoInput(true);
			conn.setRequestMethod("GET");

			if (!savePath.endsWith("/")) {
				savePath += "/";
			}
			// 鏍规嵁鍐呭绫诲瀷鑾峰彇鎵╁睍鍚�
			String fileExt = WeixinUtil.getFileEndWitsh(conn.getHeaderField("Content-Type"));
			// 灏唌ediaId浣滀负鏂囦欢鍚�
			filePath = savePath + mediaId + fileExt;

			BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
			FileOutputStream fos = new FileOutputStream(new File(filePath));
			byte[] buf = new byte[8096];
			int size = 0;
			while ((size = bis.read(buf)) != -1)
				fos.write(buf, 0, size);
			fos.close();
			bis.close();

			conn.disconnect();
			String info = String.format("涓嬭浇濯掍綋鏂囦欢鎴愬姛锛宖ilePath=" + filePath);
			System.out.println(info);
		} catch (Exception e) {
			filePath = null;
			String error = String.format("涓嬭浇濯掍綋鏂囦欢澶辫触锛�%s", e);
			System.out.println(error);
		}
		return filePath;
	}
    //绀轰緥
	@SuppressWarnings("unused")
	public static void main(String[] args) {
		/**
		 * 涓婁紶澶氬獟浣撴枃浠�
		 */
		String access_token = WeixinUtil.getAccessTokenString(ParamesAPI.corpId, ParamesAPI.secret);
		//鍦板潃
		WeixinMedia weixinMedia = uploadMedia(access_token, "image", "http://localhost:8080/weixinClient/weather1.jpg");
		//media_id
		System.out.println(weixinMedia.getMediaId());
		//绫诲瀷
		System.out.println(weixinMedia.getType());
		//鏃堕棿鎴�
		System.out.println(weixinMedia.getCreatedAt());
		//鎵撳嵃缁撴灉
		if(null!=weixinMedia){
			System.out.println("涓婁紶鎴愬姛锛�");
		}else{
			System.out.println("涓婁紶澶辫触锛�");
		}
	}

}
